/*
 * ObjectSubSystem.cpp
 *
 *  Created on: Nov 13, 2010
 *      Author: ezbe
 */

#include <vector>
#include <Logger/GlobalLogger.h>
#include <ObjectSubSystem/ObjectSubSystem.h>
#include <ObjectSubSystem/BaseObject.h>
#include <ObjectSubSystem/EmptyObject.h>

const char* ObjectSubSystem::SUBSYSTEMNAME = "ObjectSubSystem";
ObjectSubSystem * ObjectSubSystem::m_subsystem = 0;
std::vector<cleanmemproc_t> ObjectSubSystem::m_purgesystem_mem;

ObjectSubSystem::ObjectSubSystem()
{
	using namespace cvObjects;
	m_initialized = false;
	m_subsystem = 0;
	/// Register memory purge procs
	m_purgesystem_mem.push_back((cleanmemproc_t)&BaseObject::purgeMemoryPool);
	m_purgesystem_mem.push_back((cleanmemproc_t)&EmptyObject::purgeMemoryPool);
}

ObjectSubSystem::~ObjectSubSystem()
{
	shutdown();
}

bool ObjectSubSystem::initialize()
{
	if(m_initialized)
	{
		//throw error if object subsystem is allredy initialized..
	}
	m_initialized = true;
	m_subsystem = this;
	return true;
}

void ObjectSubSystem::shutdown()
{
	if(m_initialized)
	{
		LOGDEBUG("Destroying objects..");
		/// free all gameobjects.
		destroyAllObjects();

		/**
		 *	Dump memory pools.
		 */
		for(std::vector<cleanmemproc_t>::iterator it = m_purgesystem_mem.begin(); it != m_purgesystem_mem.end(); ++it)
		{
			(*it)();
		}
	}
	m_initialized = false;
	m_subsystem = 0;
}

ObjectSubSystem * ObjectSubSystem::getInstance()
{
	return m_subsystem;
}

void ObjectSubSystem::deleteObject(cvObjects::BaseObject * obj)
{
	m_objectlist.erase(obj->listItr);
	obj->destroy();
}

void ObjectSubSystem::destroyAllObjects()
{
	while(!m_objectlist.empty())
	{
		m_objectlist.back()->destroy();
		m_objectlist.pop_back();
	}
	m_objectlist.clear();
}

void ObjectSubSystem::updateObjects()
{
	// update all objects.
	// TODO: threads.
	for(baseobj_list_t::iterator it = m_objectlist.begin(); it != m_objectlist.end(); ++it)
	{
		(*it)->update();
	}
}
